package com.wjc.train.business.service.impl;

import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.wjc.train.business.entity.DailyTrainSeat;
import com.wjc.train.business.entity.TrainSeat;
import com.wjc.train.business.entity.TrainStation;
import com.wjc.train.business.repository.DailyTrainSeatRepository;
import com.wjc.train.business.repository.TrainSeatRepository;
import com.wjc.train.business.repository.TrainStationRepository;
import com.wjc.train.business.req.DailyTrainSeatQueryReq;
import com.wjc.train.business.req.DailyTrainSeatSaveReq;
import com.wjc.train.business.req.SeatSellReq;
import com.wjc.train.business.resp.DailyTrainSeatQueryResp;
import com.wjc.train.business.resp.SeatSellResp;
import com.wjc.train.business.service.IDailyTrainSeatService;
import com.wjc.train.common.enums.LogicEnum;
import com.wjc.train.common.untils.CopyUtil;
import jakarta.annotation.Resource;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.stream.Collectors;

/**
 * <p>
 * 每日座位表 服务实现类
 * </p>
 *
 * @author Guessed
 * @since 2023-08-08
 */
@Service
@Slf4j
public class DailyTrainSeatServiceImpl  implements IDailyTrainSeatService {

    @Resource
    private DailyTrainSeatRepository dailytrainseatRepository;

    @Resource
    private TrainStationRepository trainStationRepository;

    @Resource
    private TrainSeatRepository trainSeatRepository;

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void save(DailyTrainSeatSaveReq dailytrainseatSaveReq) {
        DailyTrainSeat dailytrainseat = CopyUtil.copy(dailytrainseatSaveReq, DailyTrainSeat.class);
        dailytrainseatRepository.saveOrUpdate(dailytrainseat);
    }

    @Override
    public IPage<DailyTrainSeatQueryResp> queryList(IPage<DailyTrainSeatQueryResp> page, DailyTrainSeatQueryReq dailytrainseatQueryReq) {
        return dailytrainseatRepository.queryList(page,dailytrainseatQueryReq);
    }

    @Override
    public void delete(Long id) {
        dailytrainseatRepository.getBaseMapper().deleteById(id);
    }


    @Override
    public int countSeat(Date date, String trainCode, String seatType) {
        long count = dailytrainseatRepository.lambdaQuery()
                .eq(DailyTrainSeat::getTrainCode, trainCode)
                .eq(DailyTrainSeat::getTrainDate, date)
                .eq(DailyTrainSeat::getSeatType, seatType)
                .eq(DailyTrainSeat::getIsDeleted, LogicEnum.NOT_DELETED.getCode()).count();
        //若为0则返回-1表示没这个座位类型
        return count == 0L ? -1: (int) count;
    }

    @Override
    public int countSeat(Date date, String trainCode) {
        long count = dailytrainseatRepository.lambdaQuery()
                .eq(DailyTrainSeat::getTrainCode, trainCode)
                .eq(DailyTrainSeat::getTrainDate, date)
                .eq(DailyTrainSeat::getIsDeleted, LogicEnum.NOT_DELETED.getCode()).count();
        //若为0则返回-1表示没这个座位类型
        return count == 0L ? -1: (int) count;
    }

    @Override
    public void genDaily(Date date, String trainCode) {
        log.info("开始生成日期:{},车次:{}的车座信息", DateUtil.formatDate(date),trainCode);
        //查询当日车座信息并删除
        List<DailyTrainSeat> dailyTrainSeatList = selectDailyTrainSeatByCode(date, trainCode);

        if(CollectionUtil.isNotEmpty(dailyTrainSeatList)){
            List<Long> collect = dailyTrainSeatList.stream().map(DailyTrainSeat::getId).collect(Collectors.toList());
            dailytrainseatRepository.getBaseMapper().deleteBatchIds(collect);
        }
        //查询该车次的所有车座信息
        List<TrainSeat> trainSeatList = trainSeatRepository.lambdaQuery()
                .eq(TrainSeat::getTrainCode, trainCode)
                .eq(TrainSeat::getIsDeleted, LogicEnum.NOT_DELETED.getCode()).list();
        if(CollectionUtil.isEmpty(trainSeatList)){
            log.error("该车次不存在车座信息，车次编号为:{}",trainCode);
            return;
        }

        //生成每日车座信息
//        List<DailyTrainSeat> dailyTrainSeats
//                = CopyUtil.copyList(trainSeatList, DailyTrainSeat.class);
        List<DailyTrainSeat> dailyTrainSeats = new ArrayList<>();
        trainSeatList.forEach(x->{
            DailyTrainSeat trainSeat = new DailyTrainSeat();
            trainSeat.setTrainCode(x.getTrainCode());
            trainSeat.setCarriageIndex(x.getCarriageIndex());
            trainSeat.setCarriageSeatIndex(x.getCarriageSeatIndex());
            trainSeat.setSeatType(x.getSeatType());
            trainSeat.setSeatCol(x.getCol());
            trainSeat.setSeatRow(x.getRow());
            dailyTrainSeats.add(trainSeat);
        });

        //查询车站信息，用于设置售卖初始值
        Long count = trainStationRepository.lambdaQuery()
                .eq(TrainStation::getTrainCode, trainCode)
                .eq(TrainStation::getIsDeleted, LogicEnum.NOT_DELETED.getCode()).count();

        String sell = StrUtil.fillBefore("",'0', Math.toIntExact(count)-1);
        dailyTrainSeats.forEach(x->{
            x.setId(null);
            x.setTrainDate(date);
            x.setSell(sell);
        });
        dailytrainseatRepository.saveBatch(dailyTrainSeats);
        log.info("结束生成日期:{},车次:{}的车座信息", DateUtil.formatDate(date),trainCode);
    }

    public List<DailyTrainSeat> selectDailyTrainSeatByCode(Date date, String trainCode) {
        List<DailyTrainSeat> dailyTrainSeatList =
                dailytrainseatRepository.lambdaQuery()
                        .eq(DailyTrainSeat::getTrainDate, date)
                        .eq(DailyTrainSeat::getIsDeleted, LogicEnum.NOT_DELETED.getCode())
                        .eq(DailyTrainSeat::getTrainCode, trainCode)
                        .orderByAsc(DailyTrainSeat::getCarriageSeatIndex).list();
        return dailyTrainSeatList;
    }


    @Override
    public List<SeatSellResp> querySeatSell(SeatSellReq req) {
        Date trainDate = req.getTrainDate();
        String trainCode = req.getTrainCode();
        log.info("查询日期{},车次{}的座位销售信息",DateUtil.formatDate(trainDate),trainCode);

        List<DailyTrainSeat> list = dailytrainseatRepository.lambdaQuery()
                .eq(DailyTrainSeat::getTrainCode, trainCode)
                .eq(DailyTrainSeat::getTrainDate, trainDate)
                .orderByAsc(DailyTrainSeat::getCarriageIndex)
                .orderByAsc(DailyTrainSeat::getCarriageSeatIndex).list();

        return CopyUtil.copyList(list,SeatSellResp.class);
    }
}
